# coding:utf-8
import math
import re
from time import time

from flask import current_app, jsonify

from app import executor, redisclientRemote
from app.config.setting import LOCAL_TASK, AIGC_TASK
from app.libs.AigcParseDocumentHtml import ParseDocumentHtml
from app.libs.aigc_tools import PasreArticle
from app.libs.createLocalIndex import CreatLocalIndex
from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.libs.tools import parseDocument
from app.models.aigc_content import aigc_content
from app.models.aigc_order_info import aigc_order_info
from app.models.aigc_paragraphs import AigcParagraphs
from app.models.aigc_report_info import aigc_report_info
from app.models.aigc_sentence import aigc_sentence
from app.models.base import db
from app.models.order_info import order_info
from app.models.taobao_orders import taobao_orders
from app.validators.aigc_check import AIGCArticleSubmitForm, WriterAIGCArticleSubmitForm
from app.validators.article import ReportSearchForm, AigcReportSearchForm, DeleteReportForm, WriterAigcReportSearchForm
from app.view_models.AigcReportInfo import AigcOrderInfoViewModel, AigcOrderInfolistView
from app.view_models.OrderInfo import OrderInfolistView

api = Redprint('reduce_aigc')


@api.route("/submit", methods=['POST'])
def submit():
    form = AIGCArticleSubmitForm().validate_for_api()
    current_time = str(round(time() * 1000))
    if form.file_path.data != '':
        if form.uid.data != 0:
            order_number = f'88{current_time}'
        else:
            order_number = f'8{current_time}'
    else:
        if form.uid.data != 0:
            order_number = f'99{current_time}'
        else:
            order_number = f'9{current_time}'
    with db.auto_commit():
        aigc_content_model = aigc_content()
        aigc_content_model.order_number = order_number
        aigc_content_model.content = form.content.data
        aigc_content_model.author = form.author.data
        aigc_content_model.char_sum = form.chars_sum.data
        aigc_content_model.title = form.title.data
        db.session.add(aigc_content_model)
        if form.uid.data != 0:
            report_info_model = aigc_report_info()
            report_info_model.order_number = order_number
            report_info_model.title = form.title.data
            report_info_model.author = form.author.data
            report_info_model.chars_sum = form.chars_sum.data
            report_info_model.user = form.uid.data
            db.session.add(report_info_model)
        for taobao_order in form.taobao_orders:
            info = aigc_order_info()
            info.taobao_orders = taobao_order
            info.order_number = order_number
            info.title = form.title.data
            info.chars_sum = form.chars_sum.data
            info.author = form.author.data
            info.file_path = form.file_path.data
            info.user = form.uid.data
            db.session.add(info)
    parseModel = PasreArticle(form.content.data)
    parseModel.run()
    with db.auto_commit():
        for fragment in parseModel.ArticleStruct:
            if fragment['content'].strip() != '':
                paragraphModel = AigcParagraphs()
                paragraphModel.order_number = order_number
                paragraphModel.paragraph_index = fragment['paragraph_index']
                paragraphModel.content = fragment['content'].strip()
                paragraphModel.type = fragment['type']
                db.session.add(paragraphModel)
    target_redisclient = redisclientRemote
    target_redisclient.push_task(AIGC_TASK, order_number)
    return Success()

@api.route("/writer_submit", methods=['POST'])
def writer_submit():
    form = WriterAIGCArticleSubmitForm().validate_for_api()
    current_time = str(round(time() * 1000))
    order_number = f'9{current_time}'
    with db.auto_commit():
        aigc_content_model = aigc_content()
        aigc_content_model.order_number = order_number
        aigc_content_model.content = form.content.data
        aigc_content_model.author = form.author.data
        aigc_content_model.char_sum = len(form.content.data)
        aigc_content_model.title = form.title.data
        db.session.add(aigc_content_model)
        info = aigc_order_info()
        info.taobao_orders = form.order_number.data
        info.order_number = order_number
        info.title = form.title.data
        info.chars_sum = len(form.content.data)
        info.author = form.author.data
        info.file_path = ''
        info.user = 0
        db.session.add(info)
    parseModel = PasreArticle(form.content.data)
    parseModel.run()
    with db.auto_commit():
        for fragment in parseModel.ArticleStruct:
            if fragment['content'].strip() != '':
                paragraphModel = AigcParagraphs()
                paragraphModel.order_number = order_number
                paragraphModel.paragraph_index = fragment['paragraph_index']
                paragraphModel.content = fragment['content'].strip()
                paragraphModel.type = fragment['type']
                db.session.add(paragraphModel)
    target_redisclient = redisclientRemote
    target_redisclient.push_task(AIGC_TASK, order_number)
    return Success()

@api.route('/writer_search', methods=['POST'])
def writer_search():
    form = WriterAigcReportSearchForm().validate_for_api()
    view = AigcOrderInfolistView()
    res = aigc_order_info.query.filter_by(taobao_orders=form.order_number.data).order_by(
        aigc_order_info.create_time.desc()).paginate(
        form.page.data,
        form.limit.data,
        error_out=False)
    taobaoinfo = taobao_orders.query.filter_by(order_number=form.order_number.data).first()
    remain = taobaoinfo.ai_check_remain+taobaoinfo.ai_check_unlimit_remain if taobaoinfo else 0
    view.fill(res, remain)
    return jsonify(view)

@api.route('/search', methods=['POST'])
def search():
    form = AigcReportSearchForm().validate_for_api()
    view = AigcOrderInfolistView()
    res = aigc_order_info.query.filter_by(taobao_orders=form.order_number.data).order_by(
        aigc_order_info.create_time.desc()).paginate(
        form.page.data,
        form.limit.data,
        error_out=False)
    taobaoinfo = taobao_orders.query.filter_by(order_number=form.order_number.data).first()
    remain = taobaoinfo.ai_check_remain+taobaoinfo.ai_check_unlimit_remain if taobaoinfo else 0
    view.fill(res, remain)
    return jsonify(view)


@api.route('/delete', methods=['POST'])
def delete():
    form = DeleteReportForm().validate_for_api()
    with db.auto_commit():
        aigc_order_info.query.filter_by(order_number=form.order_number.data).update({
            'is_delete': 1
        })
    return Success()

def __db_operation(sentences, content, order_number, fulltext, selffileList, checkmodel, app):
    with app.app_context():
        with db.auto_commit():
            paragraph_model = AigcParagraphs()
            sentence_model = aigc_sentence()
            target_redisclient = redisclientRemote
            paragraph_model.insert_paragrahs(content, order_number)
            sentence_model.insert_sentences(sentences, order_number)
            target_redisclient.setData(sentences, order_number, checkmodel, selffileList)
            target_redisclient.push_task(AIGC_TASK, order_number)
            check_part = ''
            for item in sentences:
                if item['check'] == 1:
                    check_part += item['content']
        print('save data complete!')


